package org.wii.base.web;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import feign.form.ContentType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.wii.base.bean.ResultBean;
import org.wii.base.exception.ParamException;
import org.wii.base.exception.constant.CommonExceptionExceptionEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author tanghong on 2022/12/23
 */
@Configuration
@AutoConfigureBefore(ErrorMvcAutoConfiguration.class)
@Slf4j
public class RestErrorViewConfiguration {

    @Bean("error")
    public View error(){
        return new View() {
            @Override
            public String getContentType() {
                return "text/html";
            }

            @Override
            public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
                if (response.isCommitted()){
                    return;
                }
                ResultBean<Object> result = ResultBean.result(new ParamException(CommonExceptionExceptionEnum.NOT_FOUND));
                response.setCharacterEncoding(CharsetUtil.UTF_8);
                response.setContentType("application/json");
                String errorResponseJsonData = JSON.toJSONString(result);
                try {
                    response.getWriter().write(errorResponseJsonData);
                } catch (IOException e) {
                    log.error("渲染Json信息错误！", e);
                }
            }
        };
    }
}
